package com.factory.iamp.service.impl;

import com.factory.iamp.dao.TableTemplateHeaderMapper;
import com.factory.iamp.pojo.TableTemplateHeader;
import com.factory.iamp.service.TableTemplateHeaderService;
import com.factory.iamp.utils.exception.APIException;
import com.factory.iamp.utils.helper.FileUploadHelper;
import com.factory.iamp.utils.helper.PageHelper;
import com.factory.iamp.utils.helper.ResponseCode;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.File;
import java.util.List;
import java.util.UUID;

@Service
@Transactional(rollbackFor = Throwable.class)
public class TableTemplateHeaderServiceImpl implements TableTemplateHeaderService {
    @Resource
    private TableTemplateHeaderMapper tableTemplateHeaderMapper;

    @Override
    public int Count(int lid) {
        return tableTemplateHeaderMapper.Count(lid);
    }

    @Override
    public int findByNameCount(String name, int lid) {
        return tableTemplateHeaderMapper.findByNameCount(name, lid);
    }

    @Override
    public List<TableTemplateHeader> ListPaged(PageHelper data, int lid) {
        return tableTemplateHeaderMapper.ListPaged(data.calOffset(), data.getLimit(), lid);
    }

    @Override
    public List<TableTemplateHeader> findByNameListPaged(PageHelper data, String name, int lid) {
        return tableTemplateHeaderMapper.findByNameListPaged(data.calOffset(), data.getLimit(), name, lid);
    }

    @Override
    public TableTemplateHeader addTableTemplateHeader(
            String name, MultipartFile file, String json, String defaultValue, int lid
    ) throws Throwable {
        if(tableTemplateHeaderMapper.findByName(name, lid) != null)
            throw new APIException(ResponseCode.DATABASE_FAILED, "已存在同名表头模板");

        String originName = file.getOriginalFilename();
        assert originName != null;
        File savedFile = FileUploadHelper.uploadedFile("/data/template/header/", file);
        String filePath = FileUploadHelper.makeFilePath(savedFile);
        TableTemplateHeader result = new TableTemplateHeader();
        result.insertBuild(name, savedFile, originName, filePath, json, defaultValue, lid);
        tableTemplateHeaderMapper.addTableTemplateHeader(result);
        return result;
    }

    @Override
    public void setJson(int oid, String json) {
        tableTemplateHeaderMapper.setJson(oid, json);
    }

    @Override
    public void deleteTableTemplateHeader(int oid, int lid) {
        TableTemplateHeader tableTemplateHeader = tableTemplateHeaderMapper.findById(oid, lid);
        FileUploadHelper.deleteFile(tableTemplateHeader.getFile_path());
        tableTemplateHeaderMapper.deleteById(oid);
    }
}
